#! /usr/bin/env python
# -*- coding: utf8 -*-
#
#  gitlab irc sender
#  Copyright (C) 2016-2017  Andrei Karas (4144)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import threading
import time

from code.configuration import Configuration
from code.core import Core

class MessageHandler(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.die = False
        self.messages = []

    def run(self):
        while (self.die == False):
            if len(self.messages) > 0:
                data = self.messages.pop()
                (channel, msg) = data
                print("irc: {0}: {1}".format(channel, msg))
                with open("{0}/{1}/in".format(Core.config.global_options.ii_server_directory, channel), "w") as w:
                    w.write(msg + "\n")
            time.sleep(Configuration.irc_message_pause)

    def split(self, channel, msg):
        arr = []
        beforeLen = len("/msg ") + len(channel) + 1
        sz = beforeLen + len(msg) + 1
        if sz <= 512:
            arr.append((channel, msg.strip()))
            return arr
        pos = 512 - beforeLen

        posSplit = msg[ : pos].rfind(" ")
        if posSplit > 0:
            pos = posSplit
        arr.append((channel, msg[ : pos].strip()))
        arr.append((channel, msg[pos : ].strip()))
        return arr

    def add(self, channel, msg):
        msg = msg.strip()
        if len(msg) == 0 or msg == "\r" or msg == "\n":
            return
        parts = self.split(channel, msg)
        for part in parts:
            # revers order
            self.messages.insert(0, part)

